<?php

session_start();
include_once( 'config.php' );
include_once( 'weibooauth.php' );



$o = new WeiboOAuth( WB_AKEY , WB_SKEY , $_SESSION['keys']['oauth_token'] , $_SESSION['keys']['oauth_token_secret']  );

$last_key = $o->getAccessToken(  $_REQUEST['oauth_verifier'] ) ;

//$_SESSION['last_key'] = $last_key;

print_r($last_key);
echo "<br>";
echo $last_key["oauth_token"];echo "<br>";
echo $last_key["oauth_token_secret"];echo "<br>";
echo $last_key["user_id"];echo "<br>";

$token = $last_key["oauth_token"];
$secret = $last_key["oauth_token_secret"];
$openid = $last_key["user_id"];

$c = new WeiboClient( WB_AKEY , WB_SKEY , $last_key['oauth_token'] , $last_key['oauth_token_secret']  );
//$ms  = $c->home_timeline(); // done
$me = $c->verify_credentials();
$nickname = $me['name'];
$sex = $me['gender'] == "f" ? 0:1;

// 注册或登录
require("../../../config/connect.php");
require("../../../public/common.php");

$sql = "select * from tsj_oauth,tsj_user where tsj_oauth.user_id=tsj_user.id and tsj_oauth.open_id='$openid' limit 1";
$result = mysql_query( $sql );
if (mysql_num_rows($result) == 0)
{
	$sql = "insert into tsj_user (nick_name, sex, is_oauth) values ('$nickname', $sex, 1)";
	mysql_query( $sql );
	if (mysql_affected_rows() == 0)
	{
		// 插入失败，提示
		exit;
	}
	else
	{
		$userid = mysql_insert_id();
		$sql = "insert into tsj_oauth (user_id,open_id,token,secret,type) values ($userid,'$openid','$token','$secret','wb')";
//		echo $sql;
		mysql_query( $sql );
		if (mysql_affected_rows() == 0)
		{
			// 插入失败，提示
			exit;
		}
	}
}
else
{
	$row = mysql_fetch_assoc( $result );
	$userid = $row["id"];
	$email = $row["email"];
}

// 登录信息
$_SESSION["isoauth"] = 1;
$_SESSION["email"] = $email;
$_SESSION["userid"] = $userid;
$_SESSION["nickname"] = $nickname;
$_SESSION["right"] = 0;

if (HasLogin())
{
	$url = "Location:http://www.tusijie.com/user";
	header($url);
	exit;
}
exit;

?>
<br />授权完成,<a href="weibolist.php">进入你的微博列表页面</a>
